package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;

import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @作者 itcast
 * @创建日期 2021/11/21 9:12
 **/
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    String webSite; // 前缀

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //1 参数校验:  分页
        dto.checkParam();
        //2. 构建查询条件
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery();
        //2.1  如果有文章标题，模糊查询  title
        if(StringUtils.isNotBlank(dto.getKeyword())){
            wrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //2.2  如果有channelId  查询 channelId
        if(dto.getChannelId()!=null){
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //2.3  如果有status  查询 status
        if(dto.getStatus()!=null){
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //2.4  如果有开始时间和结束时间  使用between 查询 publishTime 发布时间字段
        if(dto.getBeginPubDate()!=null && dto.getEndPubDate()!=null){
            wrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        //2.5 获取登录用户  使用userId查询
        WmUser user = WmThreadLocalUtils.getUser();
        if(user!=null){
            wrapper.eq(WmNews::getUserId,user.getId());
        }
        //2.6 按照createTime 降序排序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        //2.7 设置分页条件
        Page<WmNews> pageReq = new Page(dto.getPage(), dto.getSize());
        // 3. 执行查询得到结果   为host字段添加访问前缀webSite
        IPage<WmNews> pageResult = page(pageReq, wrapper);
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal(), pageResult.getRecords());
        pageResponseResult.setHost(webSite);
        return pageResponseResult;
    }
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Transactional

    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        // 1. 校验参数  封装WmNews对象
        if (StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章内容不能为空");
        }
        // 校验是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        // type字段:  当type为-1 时代表自动生成， 暂时将type设置为null
        if(WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            wmNews.setType(null); // 防止报异常
        }
        // news的封面数据库存的是字符串换  而dto的封面是字符串集合
        if(!CollectionUtils.isEmpty(dto.getImages())){
            String imagesStr = imagesToString(dto.getImages());
            wmNews.setImages(imagesStr);
        }
        wmNews.setUserId(user.getId());
        // 2. 保存或者修改
        saveOrUpdateWmNews(wmNews);
        // 如果是草稿，不用保存关联关系 直接返回
        if(WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(wmNews.getStatus())){
            return ResponseResult.okResult();
        }
        // 3. 保存 文章 和 素材的关联关系
        //3.1 抽取文章内容中所引用的图片路径集合
        List<String> contentImages = parseContentImages(dto.getContent());
        //3.2 保存内容和素材的关联关系
        if(!CollectionUtils.isEmpty(contentImages)){
            saveRelativeInfo(contentImages,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
        }
        // 3.3 保存封面和素材的关联关系
        saveRelativeInfoForCover(contentImages,wmNews,dto);


        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送 待审核消息 ==> 队列:{}, 文章id:{}",NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        // 1.参数校验
        if(id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2.根据id查询文章
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if(id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    /**
     * 保存封面和素材的关联关系
     * @param contentImages  内容中引用的图片路径
     * @param wmNews  文章
     * @param dto 请求参数
     */
    private void saveRelativeInfoForCover(List<String> contentImages, WmNews wmNews, WmNewsDTO dto) {
        // 1. 拿到前端传递过来的封面集合
        List<String> images = dto.getImages();
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            // 需要自动生成封面
            if(contentImages.isEmpty()){ // 如果没有内容图片 设置为 无封面
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }else if(contentImages.size() > 0 && contentImages.size()<=2){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);// 设置单图
                images = contentImages.stream().limit(1).collect(Collectors.toList());
            }else {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);// 设置多图
                images = contentImages.stream().limit(3).collect(Collectors.toList());
            }
            if(!CollectionUtils.isEmpty(images)){
                wmNews.setImages(imagesToString(images));
            }
            updateById(wmNews);// 更新wmNews中 图片类型  及 封面
        }
        if(!CollectionUtils.isEmpty(images)){
            // 如果封面不是自动生成，那么获取的是前端传过来的封面集合 是有前缀的  需要替换一下
            images = images.stream().map(url -> url.replaceAll(webSite,"")).distinct().collect(Collectors.toList());
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    @Autowired
    WmMaterialMapper wmMaterialMapper;

    /**
     * 保存文章和素材的关联关系
     * @param urls   素材的路径集合
     * @param newsId  文章id
     * @param type  引用类型
     */
    private void saveRelativeInfo(List<String> urls, Integer newsId, Short type) {
        // 得到素材id集合
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(urls, WmThreadLocalUtils.getUser().getId());

        // 判断素材id数量是否小于素材路径数量，如果小于说明有素材缺失，直接抛出异常
        if(CollectionUtils.isEmpty(ids)||ids.size() < urls.size()){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"相关素材不存在，发表文章失败");
        }
        // 保存素材和文章关联关系
        //  insert into 表 values (1,2,3,4), (1,2,3,4),(1,2,3,4),(1,2,3,4)，(1,2,3,4)，(1,2,3,4)
        wmNewsMaterialMapper.saveRelations(ids,newsId,type);
    }

    /**
     * String = [ {"type":"text",value:文本},{type:image,value:前缀+url路径} ]
     * List<Map>
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {
        List<Map> contentMap = JSONArray.parseArray(content, Map.class);
        return contentMap.stream() // 创建流
                .filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(map.get("type"))) // 找到type为image的数据
                .map(o -> (String) o.get("value"))  // 得到每个type为image中的 value值: 图片url路径
                .map(url -> url.replaceAll(webSite, "")) // 替换前缀路径
                .distinct() // 去除重复
                .collect(Collectors.toList());
    }

    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);// 上下架
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        if(wmNews.getId()==null){
            // 保存
            save(wmNews);
        }else {
            // 删除文章和素材的关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            // 修改
            updateById(wmNews);
        }
    }

    /**
     * [url1,url2,url3]   ===>  "url1,url2,url3"
     * @param images
     * @return
     */
    private String imagesToString(List<String> images) {
        return images.stream()
                .map(url -> url.replaceAll(webSite,""))
                .collect(Collectors.joining(","));
    }


    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if(enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable))){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，同步到app端（后期做）TODO
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                .set(WmNews::getEnable,dto.getEnable()));

    //5. 上下架发送消息通知  用于同步article 及 elasticsearch
        if (wmNews.getArticleId()!=null) {
        if(enable.equals(WemediaConstants.WM_NEWS_UP)){
            // 上架消息
            rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
        }else {
            // 下架消息
            rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,wmNews.getArticleId());
        }
    }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}


    @Autowired
    WmNewsMapper wmNewsMapper;
    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        if(StringUtils.isNotBlank(dto.getTitle())){
            dto.setTitle("%"+dto.getTitle()+"%");
        }

        //2.分页查询
        List<WmNewsVO> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }



    //todo:=====================================================================================================
    @Autowired
    WmUserMapper wmUserMapper;
    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }



    //todo:===================================================================================
    /**
     * 自媒体文章人工审核
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        // TODO 通知定时发布文章

        //5. 通知定时发布文章
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
